package me.thinkjet.staticmng.service;

import com.jfinal.kit.PathKit;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.RandomStringUtils;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

public class ImgService {


	public static final String THUMB_FLAG = "!";

	/**
	 * 检查缩略图是否存在，不存在则新建
	 */
	public static void createThumbs(String url) {
		String thumbsPath = PathKit.getWebRootPath() + url;
		if (checkThumbs(thumbsPath)) {
			return;
		} else {
			String fileContentType = url.substring(url.lastIndexOf(".") + 1);
			String descFilePath = PathKit.getWebRootPath() +
					url.substring(0, url.indexOf(THUMB_FLAG)) + "." + fileContentType;
			String[] thumbsSize = url.substring(url.indexOf(THUMB_FLAG) + 1,
					url.lastIndexOf(".")).split("x");
			int width = Integer.parseInt(thumbsSize[0]);
			int height = Integer.parseInt(thumbsSize[1]);
			if (new File(descFilePath).exists()) {
				try {
					Thumbnails
							.of(descFilePath)
							.size(height, width)
							.outputFormat(fileContentType)
							.toFile(thumbsPath);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * 根据原始URL生成缩略图Url
	 */
	public static String getThumbUrl(String url, int width, int height) {
		if (url != null
				&& !url.equals("")
				&& url.lastIndexOf(".") > 0
				&& new File(PathKit.getWebRootPath() + url).exists()) {
			StringBuffer new_url = new StringBuffer(url);
			new_url.insert(new_url.lastIndexOf("."), "!" + width + "x" + height);
			return new_url.toString();
		} else {
			return null;
		}
	}

	/**
	 * 检查缩略图是否存在
	 *
	 * @return
	 */
	public static boolean checkThumbs(String path) {
		return new File(path).exists();
	}

	/**
	 * 图片旋转
	 */
	public static void rotate() {

	}

	/**
	 * 图片裁剪
	 */
	public static void crop() {

	}
}
